﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using SCSService;
using SCS.Core.Models;
using SCS.Core.ViewModels;
using SCS.Core.Models.Collection;
using System.Data.Linq.SqlClient;
using System.Collections;

namespace SCS.Core.Controllers
{
    public class ProductController : BaseFontendController
    {
                
        #region "TypeProduct"

        public ActionResult TypeProductDetail(int id)
        {
            IntPage();
            SCSService.Type_Product type = Models.ModelsFontend.ProductModel.GetTypeProductByIdAndSiteGuid(id, DefaultSiteGuidGetter()) != null ? Models.ModelsFontend.ProductModel.GetTypeProductByIdAndSiteGuid(id, DefaultSiteGuidGetter()) : new SCSService.Type_Product();
            ViewData["IDTypeProduct"] = id;
            return View(type);
        }

        //public StringBuilder GetListTypeProductBuilder(int? id)
        //{
        //    StringBuilder sb = new StringBuilder();
        //    int siteGuid=GetSiteGuid();
            
        //    return ListTypeProductBuilder(ref sb, id,siteGuid);
        //}

        //public StringBuilder ListTypeProductBuilder(ref StringBuilder sb, int? id,int siteGuid)
        //{
        //    int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
        //    List<SCSService.Type_Product> listType = Models.ModelsFontend.ProductModel.GetListTypeProductByParentId(id, LanguageID, siteGuid);
        //    sb.Append("<ul>");
        //    foreach (var item in listType)
        //    {
        //        if (DefaultHostGetter().Contains("localhost"))
        //        {
        //            sb.Append("<li><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Product/ListProduct/" + item.TypeProductID + "'>" + item.TypeProductName + "</a>");
        //        }
        //        else
        //        {
        //            sb.Append("<li><a href='/" + DefaultLanguageGetter() + "/Product/ListProduct/" + item.TypeProductID + "'>" + item.TypeProductName + "</a>");
        //        }
                
        //        List<SCSService.Type_Product> listChild = Models.ModelsFontend.ProductModel.GetListTypeProductByParentId(item.TypeProductID,LanguageID, siteGuid);
        //        if (listChild.Count() > 0)
        //        {
        //            ListTypeProductBuilder(ref sb, item.TypeProductID,siteGuid);
        //        }
        //        sb.Append("</li>");
        //    }
        //    sb.Append("</ul>");

        //    return sb;
        //}

        //[ChildActionOnly]
        //public ActionResult MenuTypeProduct()
        //{
        //    int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
        //    int siteGuid = GetSiteGuid();

        //    ViewData["MenuTypeProduct"] = GetListTypeProductBuilder(null);

        //    ///return ket qua la 1 childAction tai 1 folder khac
        //    return PartialView("../BaseFontend/" + siteGuid + "/MenuTypeProduct");

        //}

        #endregion

        
        #region "Product"

        public ActionResult ProductDetail(int? id)
        {
            IntPage();           
            return View();
        }

        [ChildActionOnly]
        public ActionResult ProductView(int? id, string typeList, string listType)
        {
            int currentPage = 1;
            int pageSize = 9;

            if (typeList == null || typeList == string.Empty)
            {
                ViewData["typeList"] = "grid";
                typeList = "grid";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }
            ViewData["idList"] = id;
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            int? LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            SCSService.Product_Language product = Models.ModelsFontend.ProductModel.GetProductByIDAndSiteGuid(id ?? 0, DefaultSiteGuidGetter(), (int)LanguageID) != null ? Models.ModelsFontend.ProductModel.GetProductByIDAndSiteGuid(id ?? 0, DefaultSiteGuidGetter(), (int)LanguageID) : new SCSService.Product_Language();

            ViewData["IDProduct"] = id;
            
            int? currencyID = null;
            int idType = 0;
            List<Product_Language> listAnother = new List<Product_Language>();

            if (GetPriceProduct(id??0, LanguageID, currencyID) != null)
            {
                if (GetPriceProduct(id??0, LanguageID, currencyID).PriceValue != null && GetPriceProduct(id??0, LanguageID, currencyID).CurrencyID != null)
                    ViewData["PriceProduct"] = String.Format("{0:N0}", GetPriceProduct(id??0, LanguageID, currencyID).PriceValue.ToString() + " " + StockModel.GetCurrencyByID((int)GetPriceProduct(id??0, LanguageID, currencyID).CurrencyID).CurrencyCode);
                else
                    ViewData["PriceProduct"] = string.Empty;
            }
            else
                ViewData["PriceProduct"] = string.Empty;

            if (GetStockProduct(id??0) != null)
            {
                if (GetStockProduct(id??0) != null)
                {
                    ViewData["StockProduct"] = GetStockProduct(id??0) > 0 ? GetStockProduct(id??0).ToString() : "Hết hàng";
                }
                else
                    ViewData["StockProduct"] = "";
            }
            else
                ViewData["StockProduct"] = string.Empty;

            //List cac thuoc tinh cua san pham (list type Properties)
            string viewName = "";
            List<Type_Property> listTypeProperties=Models.ModelsFontend.ProductModel.GetListTypePropertiesByProductID(id??0,LanguageID??0,1);

            if (listTypeProperties.Count() > 0)
            {
                ViewData["listTypeProperties"] = listTypeProperties;
                foreach (var item in listTypeProperties)
                {
                    if (item.TypePropertiesAbstract != null && item.TypePropertiesAbstract != string.Empty)
                    {
                        viewName = item.TypePropertiesAbstract;
                        if (item.TypePropertiesAbstract == "property_comment")
                        {
                            if(Models.ModelsFontend.ProductModel.GetListProductProperties(item.TypePropertiesID, id).Count > 0)
                            {
                                ViewData["property_comment"] =  Models.ModelsFontend.ProductModel.GetListProductProperties(item.TypePropertiesID, id);
                            }
                            else
                            {
                                ViewData["property_comment"]= "Not comment";
                            }
                            
                        }
                        else
                        {
                            ViewData[viewName] = Models.ModelsFontend.ProductModel.GetListProductProperties(item.TypePropertiesID, id);
                        }
                        
                    }
                }
            }

            // cac san pham cung danh muc
            string[] arr;
            string urlOld = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : "";
            if (urlOld != "" && (urlOld.Contains("/ListProduct") || urlOld.Contains("/listproduct")))
            {
                arr = urlOld.Split('/');
                if (arr[arr.Length - 1].Contains("ListProduct") != false && arr[arr.Length - 1].Contains("listproduct") != false)
                {
                    idType = int.Parse(arr[arr.Length - 1].Contains('?') != false ? arr[arr.Length - 1] : arr[arr.Length - 1].Substring(0, arr[arr.Length - 1].IndexOf('?')));
                }
                else
                {
                    var listTypes = Models.ModelsFontend.ProductModel.ListTypeProductIDManagerByProductID(id ?? 0);
                    foreach (var it in listTypes)
                    {
                        if (Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1).Count > 1)
                        {
                            listAnother = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1);
                            int count = listAnother.Count();
                            //int index = new Random().Next(count);
                            if (count > 6)
                                listAnother = listAnother.Where(p => p.ProductID != id).Take(pageSize).ToList();
                            else
                                listAnother = listAnother.Where(p => p.ProductID != id).Take(count).ToList();

                            
                            break;
                        }
                        else
                            listAnother = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1);
                    }
                }
            }
            else
            {
                var listTypes = Models.ModelsFontend.ProductModel.ListTypeProductIDManagerByProductID(id??0);
                foreach (var it in listTypes)
                {
                    if (Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1).Count > 1)
                    {
                        listAnother = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1);
                        int count = listAnother.Count();
                        //int index = new Random().Next(count);

                        if (count > 6)
                            listAnother = listAnother.Where(p => p.ProductID != id).Take(pageSize).ToList();
                        else
                            listAnother = listAnother.Where(p => p.ProductID != id).Take(count).ToList();


                        break;
                    }
                    else
                        listAnother = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1);
                }
            }
            
            
            
            ViewData["listAnother"] = listAnother;
            ViewData["idParent"] = idType;

            //return View(product);
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/ProductView", product);
        }

        public Product_Price GetPriceProduct(int id, int? languageId,int? currencyID)
        {
            return Models.ModelsFontend.ProductModel.GetProductPriceByProductId(id, languageId,currencyID);
        }

        public long GetStockProduct(int id)
        {
            return Models.ModelsFontend.ProductModel.GetProductStockByProductId(id);
        }

        
        public ActionResult ListProduct(int? id,string typeList)
        {
            IntPage();
            return View();
        }

        public ActionResult TestList(int? id)
        {
            IntPage();
            return View();
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListProducts(int? id, string typeList)
        {
            //Id đầu vào là typeId
            int currentPage = 1;
            int pageSize = 9;

            if (typeList == null || typeList==string.Empty)
            {
                ViewData["typeList"] = "grid";
                typeList = "grid";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }
            ViewData["idList"] = id;
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            return ListProducts(currentPage, pageSize, null, id,typeList);
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListProducts(int? currentPage, int? pageSize, string gridAction, int? id, string typeList)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid =GetSiteGuid();

            if (typeList == null || typeList == string.Empty)
            {
                ViewData["typeList"] = "grid";
                typeList = "grid";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }
            //ViewData["ListTypeProduct"] = GetListTypeProductBuilder(null);

            //id đầu vào là typeId
            if (gridAction == "PageSizeChanged")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 9;
            }

            ViewData["currentPage"] = currentPage;

            var query = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(id, LanguageID, siteGuid,1).AsQueryable();
            int totalRows = query.Count();

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }

            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize,null);

            var result = query.ToList();

            if (query.Count() > 0)
            {

            }

            ViewData["idList"] = id;

            if (totalRows == 0)
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProducts", new List<SCSService.Product>());
            else
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProducts", result);
        }

        public ActionResult CreateWebshop(int? id)
        {
            return View();
        }

        [ChildActionOnly]
        public ActionResult MenuFilter(int? typeId)
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            List<SCSService.Type_Property> listFilter = Models.ModelsFontend.ProductModel.GetListFilterForTypeProduct(typeId, LanguageID, GetSiteGuid());

            ViewData["MenuFilter"] = listFilter;

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuFilter");

        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListProductsFilters(int? id, string typeList, string listType)
        {
            //Id đầu vào là typeId
            int currentPage = 1;
            int pageSize = 9;

            if (typeList == null || typeList == string.Empty)
            {
                ViewData["typeList"] = "grid";
                typeList = "grid";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }
            ViewData["idList"] = id;
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            return ListProductsFilters(id,currentPage, pageSize, null, typeList, listType);
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListProductsFilters(int? id,int? currentPage, int? pageSize, string gridAction,  string typeList,string listType)
        {
            pageSize = 9;
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            #region Check kiểm soát sim
            try
            {
                var ListTypeProduct = new ProductService().GetListTypeProductByParent(406, LanguageID, siteGuid, 1);
                ViewData["lstcombox"] = new SelectList(ListTypeProduct, "TypeProductID", "TypeProductName");
                if (id != 406 && id!=null)
                {
                    ViewData["ExitTypeProduct"] = ListTypeProduct.Where(m => m.TypeProductID == Convert.ToInt32(id)).FirstOrDefault();
                }
                else
                {
                    if (id == 406)
                    {
                        ViewData["ExitTypeProduct"] = 406;
                    }
                    else
                    {
                        ViewData["ExitTypeProduct"] = null;
                    }
                }
             
            }
            catch
            {
                ViewData["ExitTypeProduct"] = null;
            }

            #endregion

            List<Type_Property> listFilter = new List<Type_Property>();
            if (listType != string.Empty && listType != null)
            {
                if (listType.Contains(','))
                {
                    var arrID = listType.Split(',');
                    foreach (var item in arrID)
                    {
                        Type_Property ty = Models.StockModel.GetTypePropertiesById(int.Parse(item));
                        listFilter.Add(ty);
                    }
                }
                else
                {
                    Type_Property ty = Models.StockModel.GetTypePropertiesById(int.Parse(listType));
                    listFilter.Add(ty);
                }
                
            }
            

            if (typeList == null || typeList == string.Empty)
            {
                ViewData["typeList"] = "grid";
                typeList = "grid";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }
            //ViewData["ListTypeProduct"] = GetListTypeProductBuilder(null);

            //id đầu vào là typeId
            if (gridAction == "PageSizeChanged")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 9;
            }

            ViewData["currentPage"] = currentPage;

            var query = Models.ModelsFontend.ProductModel.GetListProductByTypeProductFilter(id, LanguageID, siteGuid, 1,listFilter).AsQueryable();


            #region Phầm kiếm chỉ được thực hiện khi nhấn nút tìm khiếm trong phần sim
            if (TypeSearchSim.isSearch)
            {
                TypeSearchSim.isSearch = false;
                #region tim kiem theo loai sim
                query = Models.ModelsFontend.ProductModel.GetListProductByTypeProductFilter(TypeSearchSim.idcate, LanguageID, siteGuid, 1, listFilter).AsQueryable();
                #endregion
                #region Tim theo so dien thoai
                if (!string.IsNullOrEmpty(TypeSearchSim.numberphone))
                {
                    //query = query.Where(m => m.ProductCode == numberphone);
                    query = (from sp in query
                             where sp.ProductCode.Contains(TypeSearchSim.numberphone)
                             select sp);
                }
                #endregion
                #region Tim kiem theo gia
                double dPriceStart = 0;
                double dPriceEnd = 0;
                try
                {
                    dPriceStart = double.Parse(TypeSearchSim.PriceStart);
                    dPriceEnd = double.Parse(TypeSearchSim.PriceEnd);
                }
                catch { }


                if (!string.IsNullOrEmpty(TypeSearchSim.PriceStart) && !string.IsNullOrEmpty(TypeSearchSim.PriceEnd))
                {

                    if (dPriceStart <= dPriceEnd)
                    {
                        query = (from ps in query
                                 where ps.PriceLast >= dPriceStart && ps.PriceLast <= dPriceEnd
                                 select ps);
                    }
                }
                if (!string.IsNullOrEmpty(TypeSearchSim.PriceStart) && string.IsNullOrEmpty(TypeSearchSim.PriceEnd))
                {
                    query = (from ps in query
                             where ps.PriceLast >= dPriceStart
                             select ps);
                }
                if (string.IsNullOrEmpty(TypeSearchSim.PriceStart) && !string.IsNullOrEmpty(TypeSearchSim.PriceEnd))
                {
                    query = (from ps in query
                             where ps.PriceLast <= dPriceEnd
                             select ps);
                }
                #endregion
                #region Tim kiem theo nha cung cap
                string Column = "";
                bool bl = true;
                var Products =query ;
                //var product = query;
               
                if (!string.IsNullOrEmpty(TypeSearchSim.suppliers))
                {
                    if (TypeSearchSim.suppliers.Contains(','))
                    {

                        var listSupplies = TypeSearchSim.suppliers.Split(',');
                        foreach (var item in listSupplies)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                string column = item;
                                if (bl)
                                {
                                    Products = (from ps in query
                                                where ps.ProductCode.Contains(column)
                                                select ps);
                                 
                                    bl = false;
                                }
                                else
                                {
                                    Products = Products.Union(from ps in query
                                                              where ps.ProductCode.Contains(column)
                                                   select ps);
                                }         
                            }
                           
                        }
                      
                       
                    }
                    query =Products;
                }
                #endregion

            }
            #endregion

            int totalRows = query.Count();

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }

            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize, null);

            var result = query.ToList();

            if (query.Count() > 0)
            {

            }

            ViewData["idList"] = id;

            if (totalRows == 0)
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProductsFilters", new List<SCSService.Product_Language>());
            else
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProductsFilters", result);
        }
        #endregion
        #region Ajax search sim
        public ActionResult SearchSim(string id, string suppliers, string pricestart, string priceend, string numberphone)
        {

            #region Default class TypeSearchSim
            TypeSearchSim.suppliers = "";
            TypeSearchSim.PriceStart = "";
            TypeSearchSim.PriceEnd = "";
            TypeSearchSim.numberphone = "";
            TypeSearchSim.idcate = 0;
            #endregion
            if (numberphone == "no")
            {
                numberphone = "";
            }
            TypeSearchSim.suppliers = suppliers;
            TypeSearchSim.PriceStart = pricestart;
            TypeSearchSim.PriceEnd = priceend;
            TypeSearchSim.numberphone = numberphone;
            if (string.IsNullOrEmpty(id))
            {
                id = "406";
            }
            TypeSearchSim.idcate = Int32.Parse(id);
            TypeSearchSim.isSearch = true;
            //Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Product/ListProduct/406");
            return View();

        }
        #endregion

    }
}
